<style scoped lang="scss">
    #container {
        border: 1px solid #ddd;
    }
    
    .dnd-wrap {
        border: 1px solid #ddd;
        padding-right: 20px;
        min-width: 120px;
        
        .node-box {
            display: flex;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 50px;
            border: 1px solid #ddd;
            cursor: move;
            
            .title {
                font-size: 12px;
            }
        }
        
        
    }
    
    #leftMenu {
        position: absolute;
        
        ul {
            list-style: none;
            border: 1px solid #ddd;
            margin-left: 0px;
            padding-left: 0px;;
            
            li {
                width: 120px;;
                line-height: 30px;
                cursor: pointer;
                padding-left: 5px;
                background: #fff;
                
                &:hover {
                    background: #ddd;
                }
            }
        }
        
    }
</style>
<template>
    <div style="display:flex;">
        <div class="dnd-wrap">
            <div data-type="start-event" class="node-box" @mousedown="startDrag">
                <span class="title">开始</span>
            </div>
            <div data-type="activity" class="node-box" @mousedown="startDrag">
                <span class="title">任务</span>
            </div>
            <div data-type="gateway" class="node-box" @mousedown="startDrag">
                <span class="title">网关</span>
            </div>
            <div data-type="end-event" class="node-box" @mousedown="startDrag">
                <span class="title">结束</span>
            </div>
        
        </div>
        
        <div style="flex:1;">
            <div style="margin-bottom:10px;padding: 10px;border:1px solid #ddd;border-left: none;">
                <el-button @click="triggerImportJson">导入json</el-button>
                <el-button @click="triggerJSON">导出json</el-button>
                <el-button @click="triggerSave">暂时缓存</el-button>
                <el-button @click="triggerRemote">加载数据</el-button>
            </div>
            <div style="display: flex;width: 100%">
                <div style="flex:1;">
                    <div id="container"></div>
                </div>
                <div class="rightPanel" style="background: #f0f2f5;width: 400px;
                max-height:1000px;min-height:600px;position: absolute;right: 0px;top:55px;z-index:998;">
                    123123
                </div>
            </div>
        
        </div>
        
        
        <div id="leftMenu" hidden>
            <ul>
                <li @click.stop.prevent="e=>removeNode()">删除</li>
                <li @click.stop.prevent="e=>triggerEdit()">编辑</li>
            </ul>
        </div>
    </div>
</template>
<script>
  import { init } from './g6demo.js';
  import { createRect } from './rect.js';
  import { createCircle } from './circle.js';
  import { copyToClipboard } from '@/utils/cutparse.js';
  import { alertSuccess, safeParseJson } from '@base/utils';
  import MyDialogPlus from '@codegenarate/mydialogplus';
  import axios from 'axios';
  import Hierarchy from '@antv/hierarchy';
  
  
  import { GridLayout, ForceLayout, DagreLayout, CircularLayout } from '@antv/layout';
  import { lodashUtils } from '@base/utils'; // umd模式下， const { GridLayout } = window.layout
  import lodash from 'lodash';
  
  export default {
    data() {
      return {
        graph: null,
        dnd: null,
      };
    },
    mounted() {
      var self = this;
      var { graph, dnd } = init('container');
      this.dnd = dnd;
      this.graph = graph;
      
      
      var json = sessionStorage.getItem('save_json_graph');
      //this.graph.fromJSON(safeParseJson(json));
    },
    methods: {
      startDrag(e) {
        let data = undefined;
        var node = undefined;
        var type = e.currentTarget.dataset.type;
        if (type === 'activity') {
          node = this.graph.createNode({
            shape: type,
          });
        } else if (type === 'start-event') {
          node = this.graph.createNode({
            shape: type,
            attrs: {
              label: {
                text: '开始',
              },
            },
          });
        } else if (type === 'end-event') {
          node = this.graph.createNode({
            shape: type,
            attrs: {
              label: {
                text: '结束',
              },
            },
          });
        } else if (type === 'gateway') {
          node = this.graph.createNode({
            shape: type,
          });
        }
        
        console.log('node', node, e);
        this.dnd.start(node, e);
      },
      removeNode() {
        var nodeId = sessionStorage.getItem('contextmenu_current_node_id');
        if (nodeId) {
          this.graph.removeNode(nodeId);
          document.documentElement.querySelector('#leftMenu').style.display = 'none';
        }
      },
      async triggerEdit() {
        var nodeId = sessionStorage.getItem('contextmenu_current_node_id');
        if (nodeId) {
          var cellItem = this.graph.getCellById(nodeId);
          var result = await MyDialogPlus({
            title: '导入json',
            components: {
              modify: () => import('@/dialog/importin.vue'),
            },
          });
        }
        
      },
      /**
       * @description: 暂时缓存
       * @params
       * @return
       */
      triggerSave() {
        var self = this;
        var json = self.graph.model.toJSON();
        console.log('json', json);
        copyToClipboard(JSON.stringify(json));
        alertSuccess('已复制到粘贴板上');
        sessionStorage.setItem('save_json_graph', JSON.stringify(json));
      },
      
      /**
       * @description:  加载数据
       * @params
       * @return
       */
      async triggerRemote() {
        const array = await axios.get('http://localhost:83/getNodeList').then(res => res.data).then(res => res.data);
        var nodes = [];
        var edges = [];
        for (let i = 0; i < array.length; i++) {
          var one = array[i];
          var oneNode = undefined;
          if (one.nodeName == '开始') {
            oneNode = ({
              shape: 'start-event',
              id: `${one.id}`,
              data: one,
              width: 50,
              height: 50,
              attrs: {
                width: 50,
                height: 50,
                label: { text: one.nodeName },
              },
            });
          } else if (one.nodeName == '结束') {
            oneNode = ({
              shape: 'end-event',
              id: `${one.id}`,
              data: one,
              width: 50,
              height: 50,
              attrs: {
                width: 50,
                height: 50,
                label: { text: one.nodeName },
              },
            });
          } else {
            oneNode = ({
              shape: 'activity',
              id: `${one.id}`,
              data: one,
              width: 100,
              height: 50,
              label: `${one.id}--${one.nodeName}`,
              attrs: {
                width: 100,
                height: 50,
              },
            });
          }
          
          nodes.push(oneNode);
          
        }
        
        
        for (let i = 0; i < array.length; i++) {
          var nodeitem = array[i];
          var  currentNodeId=""
          var parentId = '';
          
          
          if (nodeitem.confluenceType == 5) {
            currentNodeId = nodeitem.confluenceId + '';
            parentId = nodeitem && nodeitem.id;
          } else {
            currentNodeId = nodeitem&&nodeitem.id + '';
            parentId = nodeitem.parentNodeId + '';
          }
          
          var parentExit = lodash.find(array, item => item.id == parentId);
          console.log("parentnode ",parentId,parentExit&&parentExit.nodeName);
  
  
          if (!(parentExit && parentExit.id)) {
            continue;
          }
          if (nodeitem.id) {
            edges.push({
              source: {
                cell: `${parentId}`,
                port: 'port3',
              },
              target: {
                cell: `${currentNodeId}`,
                port: 'port1',
              },
            });
          }
          
          
          /*如果是虚拟节点  还需要填充 一条单线*/
          if(nodeitem.confluenceType==5){
            var parentExit2 = lodash.find(array, item => item.id == nodeitem.parentNodeId);
            if(parentExit2&&parentExit2.id){
              edges.push({
                source: {
                  cell: `${parentExit2.id}`,
                  port: 'port3',
                },
                target: {
                  cell: `${nodeitem.id}`,
     
                  port: 'port1',
                },
              });
            }
           
          }
          
        }
        
        
        /*
         添加 连再一起的线条
         graph.addEdge({
           source,
           target,
         })*/
        
        
        const model = { nodes, edges };
        //  处理 modal x y
        
        /*        const dagreLayout = new DagreLayout({
                  //type: 'dagre',
                  type: 'dendrogram',
                  rankdir: 'LR',
                  align: 'UR',
                  ranksep: 35,
                  nodesep: 15,
                });
                const newmodel = dagreLayout.layout(model);*/
        
        
        /*    const circularLayout = new CircularLayout({
              type: 'circular',
              center: [350, 250],
            })
            const newmodel = circularLayout.layout(model)*/
        
        
        /*       const gridLayout = new GridLayout({
                 type: 'grid',
                 width: 738,
                 height: 360,
                 sortBy: 'label',
                 rows: 3,
                 cols: 7,
               })
         
               const newmodel = gridLayout.layout(model)*/
        
        
        var layout = new DagreLayout({
          type: 'dagre',
          rankdir: 'T', // 可选，默认为图的中心
        });
        const newmodel = layout.layout(model);
        this.graph.fromJSON(newmodel);
        
        
        return array;
      },
      
      triggerJSON() {
        var self = this;
        var json = self.graph.model.toJSON();
        console.log('json', json);
        copyToClipboard(JSON.stringify(json));
        alertSuccess('已复制到粘贴板上');
      },
      async triggerImportJson() {
        
        var result = await MyDialogPlus({
          title: '导入json',
          components: {
            modify: () => import('@/dialog/importin.vue'),
          },
          
        });
        if ((result && result.success)) {
          var json = JSON.parse(result.data);
          this.graph.fromJSON(json);
          alertSuccess('导入成功');
          
        }
        
      },
      
    },
  };
</script>
